﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.IO;
using System.Collections;
using System.Text.RegularExpressions;



namespace Usas.Common.Cms
{
    public class FileControl : System.Web.UI.Page
    {

        private ArrayList GetFileNameAndFormat(string fu)
        {
            string[] FileName = fu.Split('.');
            return new ArrayList() { FileName[0], FileName[FileName.Length - 1] };
        }


        private string CreateDir(string path)
        {
            DateTime dt = DateTime.Now;
            string year = dt.Year.ToString();
            string month = dt.Month.ToString();
            string day = dt.Day.ToString();
            string Dir = "";
            if (!new DirectoryInfo(path + year).Exists)
            {
                Directory.CreateDirectory(path + year);
                Dir = year;
            }
            else
            {
                Dir = year;
            }
            if (!new DirectoryInfo(path + year + @"\" + month).Exists)
            {
                Directory.CreateDirectory(path + year + @"\" + month);
                Dir = year + @"\" + month;
            }
            else
            {
                Dir = year + @"\" + month;
            }
            if (!new DirectoryInfo(path + year + @"\" + month + @"\" + day).Exists)
            {
                Directory.CreateDirectory(path + year + @"\" + month + @"\" + day);
                Dir = year + @"\" + month + @"\" + day;
            }
            else
            {
                Dir = year + @"\" + month + @"\" + day;
            }
            return Dir;
            //string FilePath = path + year + @"\" + month + @"\" + DateTime.Now.ToFileTime() + @"." + FileType;
        }

        public bool IsData(string name)
        {
            if (name != "")
            {

                string[] filetype = name.Split('.');
                if (filetype[filetype.Length - 1] != "Mhm")
                {
                    //ExecleDs(path + "temp.xls", dt);
                    return false;
                }
                else
                {
                    return true;
                }
            }
            else
            {
                return false;
            }

        }

        public ArrayList UpdateFile(bool isRead, string dir, string filename, string content, FileUpload fu, string fn)
        {

            string temppath = System.Configuration.ConfigurationManager.AppSettings["UsasInformationPath"] + "CMSUpLoadFiles\\";
            if (temppath.IndexOf(":") == -1)
            {
                temppath = System.Web.HttpContext.Current.Server.MapPath(temppath);
            }

            try
            {
                string backfile;
                string backdir;
                if (isRead)
                {
                    if (dir == null && filename == null)
                    {
                        backfile = fn + ".Mhm";

                        backdir = CreateDir(temppath);

                        temppath = temppath + backdir + @"\" + backfile;

                        FileStream fs = File.Create(temppath);

                        fs.Close();
                    }
                    else if (!System.IO.File.Exists(temppath + dir + @"\" + filename))
                    {
                        backfile = fn + ".Mhm";
                        backdir = CreateDir(temppath);

                        temppath = temppath + backdir + @"\" + backfile;

                        FileStream fs = File.Create(temppath);

                        fs.Close();

                    }
                    else
                    {
                        string fm = GetFileNameAndFormat(filename)[1].ToString();

                        if (fm != "Mhm")
                        {
                            backfile = fn + ".Mhm";
                            backdir = CreateDir(temppath);

                            temppath = temppath + backdir + @"\" + backfile;
                            FileStream fs = File.Create(temppath);
                            fs.Close();


                        }
                        else
                        {
                            temppath = temppath + dir + @"\" + filename;

                            backfile = filename;
                            backdir = dir;
                        }
                    }

                    StreamReader sr = new StreamReader(temppath);
                    string str = sr.ReadToEnd();
                    sr.Close();

                    string NContent = content.ToLower().Replace(@"\", "").Replace("\"", "");
                    string NStr = str.ToLower().Replace(@"\", "").Replace("\"", "");

                    if (NContent != NStr)
                    {
                        str = content;

                        StreamWriter sw = new StreamWriter(temppath, false);
                        sw.WriteLine(str);

                        sw.Flush();
                        sw.Close();

                        return new ArrayList() { backdir, backfile };
                    }
                    else
                    {
                        return null;
                    }

                }
                else
                {
                    if (fu.HasFile)
                    {
                        string fm = GetFileNameAndFormat(fu.FileName)[1].ToString();

                        backfile = fn + "." + fm;
                        backdir = CreateDir(temppath);

                        string saveAs = temppath + backdir + @"\" + backfile;

                        fu.SaveAs(saveAs);
                        try
                        {
                            UsasCmsCommon.OfficeConvert oc = new UsasCmsCommon.OfficeConvert();
                            switch (fm.ToLower())
                            {
                                case "doc":
                                    oc.ConvertWORD(saveAs, temppath + backdir + @"\" + fn + ".html");
                                    break;
                                case "xls":
                                    oc.ConvertEXCEL(saveAs, temppath + backdir + @"\" + fn + ".html");
                                    break;
                            }
                        }
                        catch (Exception ex)
                        {

                        }
                        return new ArrayList() { backdir, backfile };

                    }
                    else
                    {
                        return null;
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
                return null;
            }
        }


        /// <summary>

        /// 去除HTML标记

        /// </summary>

        /// <param name="NoHTML">包括HTML的源码 </param>

        /// <returns>已经去除后的文字</returns>

        public string NoHTML(string Htmlstring)
        {

            //删除脚本

            Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);

            //删除HTML

            Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);

            Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);

            Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);

            Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);



            Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);

            Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);

            Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);

            Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);

            Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);

            Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);

            Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);

            Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);

            Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);

            Htmlstring = Regex.Replace(Htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase);



            Htmlstring.Replace("<", "");

            Htmlstring.Replace(">", "");

            Htmlstring.Replace("\r\n", "");

            Htmlstring = HttpContext.Current.Server.HtmlEncode(Htmlstring).Trim();



            return Htmlstring;

        }


        public void OnlySee(Panel pn, bool istop, string filepath, string type)
        {

            FileInfo fn = new System.IO.FileInfo(System.Configuration.ConfigurationManager.AppSettings["UsasInformationPath"].ToString() + "CMSUpLoadFiles\\" + filepath.Replace("/", @"\"));

            if (fn.Exists)
            {
                if (type == ".pdf")
                {
                    Literal li = new Literal();
                    li.Text = "<OBJECT id='AcroPDF' style='WIDTH: 100%; HEIGHT: 700px' classid='clsid:CA8A9780-280D-11CF-A24D-444553540000'" +
                                "name='AcroPDF1' VIEWASTEXT>" +
                        //"<PARAM NAME='src' VALUE='" + Request.Url.Scheme + "://" + Request.Url.Authority + "/UsasInformation/CMSUpLoadFiles/" + filepath + "'>" +
                               "<PARAM NAME='src' VALUE='" + System.Configuration.ConfigurationManager.AppSettings["UsasInformationIIS"].ToString() + "CMSUpLoadFiles/" + filepath + "'>" +
                               "</OBJECT> <script>var AcroPDF1 = document.getElementById('AcroPDF');AcroPDF1.setShowToolbar(false);AcroPDF1.setShowScrollbars(true);</script>";


                    pn.Controls.Add(li);
                }
                else if (type == ".DWF" || type == ".dwf")
                {
                    Literal li = new Literal();
                    li.Text = "<OBJECT id='AcroPDF' style='WIDTH: 100%; HEIGHT: 700px' classid='clsid:A662DA7E-CCB7-4743-B71A-D817F6D575DF'>" +
                                 "<PARAM NAME='src' VALUE='" + System.Configuration.ConfigurationManager.AppSettings["UsasInformationIIS"].ToString() + "CMSUpLoadFiles/" + filepath + "'>" +
                            "</OBJECT> ";


                    pn.Controls.Add(li);
                }
                else if (type == ".xls" || type == ".doc")
                {
                    Literal li = new Literal();
                    string rp = System.IO.Path.GetExtension(filepath);
                    string ur = System.Configuration.ConfigurationManager.AppSettings["UsasInformationIIS"].ToString() +
                        "CMSUpLoadFiles/" + filepath.Replace(rp, ".html");
                    li.Text = "<div id='Iframe' style='display:none'><IFRAME id='AcroPDF' style='WIDTH: 100%; HEIGHT: 700px' name='office' src='"
                        + ur + "' border='0'> </IFRAME></div><script language='JavaScript'>IframeExist('" + ur + "')</script>";

                    pn.Controls.Add(li);
                }
                else
                {
                    ImageButton hy = new ImageButton();
                    hy.Attributes.Add("onclick", "window.open('" + System.Configuration.ConfigurationManager.AppSettings["UsasInformationIIS"].ToString() + "CMSUpLoadFiles/" + filepath + "');return false");
                    hy.ImageUrl = "~/CMS/images/dd.gif";

                    pn.Controls.Add(hy);
                }
            }
            else
            {
                Literal li = new Literal();
                li.Text = "<br><h1>文件不存在</h1>";
                pn.Controls.Add(li);
            }
            //string tips = Path.GetExtension(url);

            //string furl = IsTopFolder ? "" : "../";
            //lb.Attributes.Add("onclick", "window.open('" + furl + "Attachment.aspx?topic=" + topic
            //    + "&address=" + url + "&suf=" + suf + "','附件', 'width=900,height=600,toolbar=no, menubar=no, scrollbars=yes,status=no,resizable=yes,top=100');return false");
        }

        public void OnlySee(Panel pn, bool istop, string filepath, string type, bool download)
        {

            FileInfo fn = new System.IO.FileInfo(System.Configuration.ConfigurationManager.AppSettings["UsasInformationPath"].ToString() + "CMSUpLoadFiles\\" + filepath.Replace("/", @"\"));

            if (fn.Exists)
            {
                if (download)
                {
                    ImageButton hy = new ImageButton();
                    hy.Attributes.Add("onclick", "window.open('" + System.Configuration.ConfigurationManager.AppSettings["UsasInformationIIS"].ToString() + "CMSUpLoadFiles/" + filepath + "');return false");
                    hy.ImageUrl = "~/CMS/images/dd.gif";

                    pn.Controls.Add(hy);
                }

                if (type == ".pdf")
                {


                    Literal li = new Literal();
                    li.Text = "<br/><br/><OBJECT id='AcroPDF' style='WIDTH: 100%; HEIGHT: 900px' classid='clsid:CA8A9780-280D-11CF-A24D-444553540000'" +
                                "name='AcroPDF1' VIEWASTEXT>" +
                        //"<PARAM NAME='src' VALUE='" + Request.Url.Scheme + "://" + Request.Url.Authority + "/UsasInformation/CMSUpLoadFiles/" + filepath + "'>" +
                               "<PARAM NAME='src' VALUE='" + System.Configuration.ConfigurationManager.AppSettings["UsasInformationIIS"].ToString() + "CMSUpLoadFiles/" + filepath + "'>" +
                               "</OBJECT> <script>var AcroPDF1 = document.getElementById('AcroPDF');AcroPDF1.setShowToolbar(false);AcroPDF1.setShowScrollbars(true);</script>";


                    pn.Controls.Add(li);
                }
                else if (type == ".DWF" || type == ".dwf")
                {

                    Literal li = new Literal();
                    li.Text = "<br/><br/><OBJECT id='AcroPDF' style='WIDTH: 100%; HEIGHT: 900px' classid='clsid:A662DA7E-CCB7-4743-B71A-D817F6D575DF'>" +
                                 "<PARAM NAME='src' VALUE='" + System.Configuration.ConfigurationManager.AppSettings["UsasInformationIIS"].ToString() + "CMSUpLoadFiles/" + filepath + "'>" +
                            "</OBJECT> ";


                    pn.Controls.Add(li);
                }
                else if (type == ".xls" || type == ".doc")
                {



                    Literal li = new Literal();
                    string rp = System.IO.Path.GetExtension(filepath);
                    string ur = System.Configuration.ConfigurationManager.AppSettings["UsasInformationIIS"].ToString() +
                      "CMSUpLoadFiles/" + filepath.Replace(rp, ".html");
                    li.Text = "<br/><br/><div id='Iframe' style='display:none'><IFRAME id='AcroPDF' style='WIDTH: 100%; HEIGHT: 900px' name='office' src='"
                        + ur + "' border='0'> </IFRAME></div><script language='JavaScript'>IframeExist('" + ur + "')</script>";

                    pn.Controls.Add(li);
                }

            }
            else
            {
                Literal li = new Literal();
                li.Text = "<br><h1>文件不存在</h1>";
                pn.Controls.Add(li);
            }
        }

    }

}
